package com.lhq.tag_tales.config;

import com.lhq.tag_tales.interceptor.UserContextInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfig implements WebMvcConfigurer {
    // 当前跨域请求最大有效时长。这里默认1天
    private static final long MAX_AGE = 24 * 60 * 60;

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                // 设置允许跨域请求的域名
                .allowedOrigins("http://localhost:8000","http://localhost:8090")
                // 是否允许证书
                .allowCredentials(true)
                // 设置允许的方法
                .allowedMethods("*")
                // 设置允许的header
                .allowedHeaders("*")
                // 跨域允许时间
                .maxAge(MAX_AGE);
    }

    @Override   // 配置拦截器
    public void addInterceptors(InterceptorRegistry registry) {
        // 对swagger的请求不进行拦截
        String[] excludePatterns = new String[]{"/swagger-resources/**", "/webjars/**", "/v2/**", "/swagger-ui.html/**",
                "/api", "/api-docs", "/api-docs/**", "/doc.html/**","/user/login","/user/register"};
        registry.addInterceptor(new UserContextInterceptor())
                // 拦截所有请求
                .addPathPatterns("/**")
                // 排除指定请求
                .excludePathPatterns(excludePatterns);
    }
}
